package com.jokey.vue.configuate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jokey.vue.model.RespBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author JokeyFeng
 * @date: 2021/11/27
 * @project: vuehr
 * @package: com.jokey.vue.configuate
 * @comment: 认证失败处理器
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException e) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        RespBean respBean;
        if (e instanceof BadCredentialsException) {
            respBean = RespBean.build().setMsg("尚未登录，请登录");
        } else if (e instanceof UsernameNotFoundException) {
            respBean = RespBean.error("账户名或密码输入错误！");
        } else if (e instanceof LockedException) {
            respBean = RespBean.error("账户被锁定，请联系管理员！");
        } else if (e instanceof CredentialsExpiredException) {
            respBean = RespBean.error("密码过期，请联系管理员！");
        } else if (e instanceof AccountExpiredException) {
            respBean = RespBean.error("账户过期，请联系管理员！");
        } else if (e instanceof DisabledException) {
            respBean = RespBean.error("账户被禁用，请联系管理员！");
        } else {
            respBean = RespBean.error("登录失败");
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(respBean));
        writer.flush();
        writer.close();
    }
}
